package com.victor.common.security.aspect;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class PageAspect implements InnerInterceptor {
    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        BoundSql boundSql = sh.getBoundSql();
        String originalSql = boundSql.getSql();
        // 检查是否为分页查询
        if (originalSql.contains("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY")) {
            // 确保 OPTION (RECOMPILE) 放在查询的最后
            if (!originalSql.trim().toUpperCase().endsWith("OPTION (RECOMPILE)")) {
                String modifiedSql = originalSql + " OPTION (RECOMPILE)";
                // 使用反射设置新的 SQL 语句
                ReflectUtil.setFieldValue(boundSql, "sql", modifiedSql);
            }
        }
    }
}
